package com.vipboot.framework.embedded.redis.autoconfig;

import com.github.fppt.jedismock.RedisServer;
import com.vipboot.framework.redis.autoconfig.RedissonAutoConfig;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.core.Ordered;

import java.io.IOException;

@Slf4j
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@AutoConfiguration(before = {RedissonAutoConfig.class})
public class EmbeddedRedisAutoConfig {

    @Value("${spring.data.redis.host}")
    private String host = "localhost";

    @Value("${spring.data.redis.port}")
    private Integer port = 6379;

    private RedisServer redisServer;

    //    public EmbeddedRedisAutoConfig() {
//        redisServer = RedisServer.newRedisServer(port);
//    }
    @PostConstruct
    public void postConstruct() throws IOException {
        log.info("初始化 EmbeddedRedisAutoConfig");
        redisServer = RedisServer.newRedisServer(port);
        log.info("启动 嵌入式Redis");
        redisServer.start();
    }

    @PreDestroy
    public void preDestroy() throws IOException {
        log.info("关闭 嵌入式Redis");
        redisServer.stop();
    }
}
